package com.xhh.reapply.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.utils.thread.ThreadLocalUtil;
import com.xhh.apis.check.ICheckClient;
import com.xhh.apis.user.IUserClient;
import com.xhh.common.constants.CheckedConstants;
import com.xhh.common.constants.ScoreConstants;
import com.xhh.common.constants.StudentConstants;
import com.xhh.model.check.vos.CheckedVo;
import com.xhh.model.common.dtos.PageResponseResult;
import com.xhh.model.common.dtos.ResponseResult;
import com.xhh.model.common.enums.AppHttpCodeEnum;
import com.xhh.model.reapply.dtos.FiltrateStudentDto;
import com.xhh.model.reapply.pojos.Score;
import com.xhh.model.reapply.vos.FilterStuVo;
import com.xhh.model.reapply.vos.StudentInfoVo;
import com.xhh.model.user.pojos.Student;
import com.xhh.model.user.pojos.User;
import com.xhh.reapply.mapper.ScoreMapper;
import com.xhh.reapply.service.IScoreService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2024-08-03
 */
@Service
@RequiredArgsConstructor
public class ScoreServiceImpl extends ServiceImpl<ScoreMapper, Score> implements IScoreService {

    private final ICheckClient checkClient;
    private final IUserClient userClient;

    /**
     * 分页条件查询考生信息
     * @param dto
     * @return
     */
    @Override
    public ResponseResult filtrateStudent(FiltrateStudentDto dto) {
        // 1. 校验参数
        if (dto == null || StrUtil.isEmpty(dto.getUnityCode())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        // 2 校验用户身份
        // 2.1 获取登录用户的id
        User user = ThreadLocalUtil.getUser();
        Long userId = user.getId();
        // 2.2 校验身份
        ResponseResult responseResult = checkClient.checkIdentity(userId);
        String jsonStr = (String) responseResult.getData();
        CheckedVo checked = JSONObject.parseObject(jsonStr, CheckedVo.class);
        // 招生单位
        if (!checked.getIdentityCode().equals(CheckedConstants.SCHOOL_IDENTITY_CODE)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        // 3. 构建分页条件
        Page<FilterStuVo> page = new Page<>(dto.getPage(), dto.getSize());

        List<FilterStuVo> records = baseMapper.selectStuInfo(dto);
        page.setRecords(records);
        page.setTotal(records.size());
        // 4. 返回结果
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        pageResponseResult.setData(page.getRecords());
        return ResponseResult.okResult(pageResponseResult);
    }

    /**
     * 根据准考证号获取考生成绩信息
     * @param stuCode
     * @return
     */
    @Override
    public ResponseResult getScoreByCode(String stuCode) {
        // 1. 校验参数
        if (StrUtil.isEmpty(stuCode)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 构建查询条件
        Score score = lambdaQuery()
                .eq(Score::getStuCode, stuCode)
                .one();
        if (score == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 3. 返回结果
        return ResponseResult.okResult(score);
    }

    /**
     * 根据考生号查看学生详情
     * @param studentCode
     * @return
     */
    @Override
    public ResponseResult getStuInfoById(String studentCode) {
        // 1. 校验参数
        if (StrUtil.isEmpty(studentCode)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 构造查询
        // 2.1 查询分数表
        ResponseResult result = getScoreByCode(studentCode);
        String json = JSON.toJSONString(result.getData());
        Score score = JSONObject.parseObject(json, Score.class);
        if (score == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 2.2 拿到分数表的学生id，查询学生基本信息
        ResponseResult responseResult = userClient.getStuByCode(studentCode);
        if (!responseResult.getCode().equals(200) || responseResult.getData() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        String jsonStr = JSON.toJSONString(responseResult.getData());
        Student baseInfo = JSONObject.parseObject(jsonStr, Student.class);
        // 3. 返回结果
        StudentInfoVo studentInfo = new StudentInfoVo();
        studentInfo.setBaseInfo(baseInfo);
        studentInfo.setScore(score);
        return ResponseResult.okResult(studentInfo);
    }

    /**
     * 判断考生是否上线
     * @param userId
     * @return
     */
    @Override
    public ResponseResult isOnline(Long userId) {
        // 1. 校验参数
        // 1.1 空参校验
        if (userId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 1.2 校验身份
        ResponseResult responseResult = checkClient.checkIdentity(userId);
        String jsonStr = (String) responseResult.getData();
        CheckedVo checked = JSONObject.parseObject(jsonStr, CheckedVo.class);
        // 学生
        if (!checked.getIdentityCode().equals(CheckedConstants.STUDENT_IDENTITY_CODE)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        // 获取准考证号
        ResponseResult res = userClient.getStuByUId(userId);
        String string = JSON.toJSONString(res.getData());
        Student student = JSONObject.parseObject(string, Student.class);
        if (student == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 2. 构建查询条件
        HashMap<String, String> resultMap = new HashMap<>();
        String onlineResult = ScoreConstants.ONLINE_RESULT_PASS;
        // 一分区
        Score score = lambdaQuery()
                .eq(Score::getStuCode, student.getStuNo())
                .gt(Score::getTotal, ScoreConstants.TOTAL_ONE_ZONE_ONLINE_DEMAND)
                .gt(Score::getZzllScore, ScoreConstants.ZZLL_ONE_ZONE__ONLINE_DEMAND)
                .gt(Score::getWgyScore, ScoreConstants.WGY_ONE_ZONE__ONLINE_DEMAND)
                .gt(Score::getYwk1Code, ScoreConstants.YWK1_ONE_ZONE__ONLINE_DEMAND)
                .gt(Score::getYwk2Code, ScoreConstants.YWK2_ONE_ZONE__ONLINE_DEMAND)
                .one();
        if (score == null) {
            onlineResult = ScoreConstants.ONLINE_RESULT_NOT_PASS;
            resultMap.put("onlineResult", onlineResult);
            return ResponseResult.okResult(resultMap);
        }
        // 3. 返回结果
        resultMap.put("onlineResult", onlineResult);
        return ResponseResult.okResult(resultMap);
    }
}
